<?php
namespace Home\Controller;

use Home\Model\UseReturnModel;
use Home\Model\OfficeStationeryModel;
use Home\Model\InventoryInformationModelModel;
use Home\Model\ApplicationFormModel;

class UseReturnController extends CommonController{
	
	protected $table="use_return";
  protected $pageSize = 12;
  
  public function index(){
		$type = D('OfficeStationery')->where(array('info_status'=>1,'belongs_department'=>D('ApplicationForm')->getSelfDepartment()))->select();
		
		$this->assign('type', arr_to_map($type,type,true));
		$this->assign('name', arr_to_map($type,name,true));
		$this->assign('unit', arr_to_map($type,unit,true));
		$this->assign('specification', arr_to_map($type,specification,true));
		$this->assign('app_names', D('ApplicationForm')->getAllCrmNames());
		$this->assign('belongsDepartment',D('ApplicationForm')->getSelfDepartments());
		$this->assign('departName',D('ApplicationForm')->getSelfDepartment());
  	$this->display();
  }


public function getList(){
	$this->setQeuryCondition();
    $count = (int)$this->M->count();
    $this->setQeuryCondition();
    $list = $this->M->page(I('get.p',0). ','. $this->pageSize)->order('id desc')->select();
    
	foreach ($list as $k => $v) {
    	$list[$k]['type']=M('office_stationery')->where(array('name'=>$v['name'],'specification'=>$v['specification'],'unit'=>$v['unit']))->getField('type');
    }
	foreach ($list as $k => $v) {
    	$list[$k]['price']=M('storage_detail')->where(array('name'=>$v['name'],'specification'=>$v['specification'],'unit'=>$v['unit']))->getField('price');
    }
	
	foreach ($list as $k => $v) {
    	$list[$k]['sum']= $list[$k]['price'] * $list[$k]['use_num'];
		$list[$k]['sum'] = sprintf("%.2f", $list[$k]['sum']);
    }
	
	
    $result = array('list'=>$list, 'count'=>$count);
		$this->ajaxReturn($result);

	}

 	//设置查询
  public function setQeuryCondition(){
  	if (isset($_GET['belongs_department'])) {
		$this->M->where(array("belongs_department"=> array('EQ', I('get.belongs_department'))));
	}else{
		$this->M->where(array("belongs_department"=> array('EQ', D('ApplicationForm')->getSelfDepartment())));
	}

	if (I('get.type')) {
		$this->M->where(array("type"=> array('EQ', I('get.type'))));
	}
	
	
	if (I('get.name')) {
		$this->M->where(array("name"=> array('like', "%".I('get.name')."%")));
	}
	
	if (I('get.app_name')) {
		$this->M->where(array("app_name"=> array('EQ',I('get.app_name'))));
	}
	
	if (I('get.start1') && I('get.start2')) {
		$start1 = I('get.start1');
		$start2 = I('get.start2');
		$d = date('Y-m-d',strtotime($start2)+86400);
		$this->M->where(array("use_time"=> array('between', "$start1,$d")));
	}
	
	if (I('get.end1') && I('get.end2')) {
		$end1 = I('get.end1');
		$end2 = I('get.end2');
		$d = date('Y-m-d',strtotime($end2)+86400);
		$this->M->where(array("return_time"=> array('between', "$end1,$d")));
	}
	
    $this->M->where( array('info_status'=>array('EQ', 1) ) );

  }

	
	/**
	 * 新增一条数据
	 */

    public function add(){
    	//查询库存是否还有
    	$num = D('InventoryInformation')->where(array('name'=>$_POST['name'],'unit'=>$_POST['unit'],'specification'=>$_POST['specification'],'belongs_department'=>D('ApplicationForm')->getSelfDepartment()))->getField('inventory_num');
		if($num==0){
			$this->error('该物品库存量为零，请重新选择物品！');
		}
		$_POST['belongs_department'] = D('ApplicationForm')->getSelfDepartment();
    	$re = $this->M->create($_POST, 1);
		
    	if($re){
    		if($re['use_num']===0){
    			$this->error('当前领用数量为0');
    		}else{
    			$this->M->startTrans(); //开启事务
    		
	    		//构造插入库存数据表的数据
	    		$result = array();
				$result['name'] = $re['name'];
				$result['unit'] = $re['unit'];
				$result['specification'] = $re['specification'];
				//查询用品资料表，获取类型，价格等数据
				$res = D('officeStationery')->where(array('name'=>$result['name'],'unit'=>$result['unit'],'specification'=>$result['specification'],'belongs_department'=>D('ApplicationForm')->getSelfDepartment()))->select();
				if(!$res){
					$this->M->rollback();
					$this->error($this->M->getError());
				}else{
					$result['type'] = $res[0]['type'];
				    $result['price']= $res[0]['price'];
				}
				
				//查询当前库存表是否已经存在该用品
				$relt = D('inventoryInformation')->where(array('name'=>$result['name'],'unit'=>$result['unit'],'specification'=>$result['specification'],'belongs_department'=>D('ApplicationForm')->getSelfDepartment()))->select();
				if($relt){
				    $result['inventory_num'] = $relt[0]['inventory_num'] - $re['use_num'] + $re['return_num'];//库存数量减去领用数量加上归还数量
					$result['use_num'] = $relt[0]['use_num'] + $re['use_num'] ;//领用数量等于当前领用数量加上新增领用数量
					$result['return_num'] = $relt[0]['return_num'] + $re['return_num'] ;//归还数量等于当前归还数量加上新增归还数量
					$result['using_num']  = $relt[0]['total_num'] - $result['inventory_num'];
					if (M('inventoryInformation')->where(array('name'=>$result['name'],'unit'=>$result['unit'],'specification'=>$result['specification'],'belongs_department'=>D('ApplicationForm')->getSelfDepartment()))->save($result) !== false) {
						$this->M -> add();
						$this->M->commit();
						$this->success(L('ADD_SUCCESS'));
					} else {
						$this->M->rollback();
						$this->error($this->M->getError().$this->M->getLastSql());
					}
					
				}else{
					
					$this->M->rollback();
					$this->error("该用品库存为空".$this->M->getLastSql());
					
				}
    		}
    		
			
			
    	}else{
    		$this->error($this->M->getError());
    	}
    }


/**
 * 新增归还
 * 
 */

    public function returns(){
    	//查询正在使用的最大数量
    	$num = D('InventoryInformation')->where(array('name'=>$_POST['name'],'unit'=>$_POST['unit'],'specification'=>$_POST['specification'],'belongs_department'=>D('ApplicationForm')->getSelfDepartment()))->getField('using_num');
    	if($num==0){
    		$this->error('当前物品已全数归还！');
    	}
		$_POST['belongs_department'] = D('ApplicationForm')->getSelfDepartment();
    	$re = $this->M->create($_POST, 1);
		
    	if($re){
    		if($re['return_num']===0){
    			$this->error('当前归还数量为0');
    		}else{
    			$this->M->startTrans(); //开启事务
    		
	    		//构造插入库存数据表的数据
	    		$result = array();
				$result['name'] = $re['name'];
				$result['unit'] = $re['unit'];
				$result['specification'] = $re['specification'];
				
				//查询用品资料表，获取类型，价格等数据
				$res = D('useReturn')->where(array('name'=>$result['name'],'unit'=>$result['unit'],'specification'=>$result['specification'],'belongs_department'=>D('ApplicationForm')->getSelfDepartment()))->select();
				if(!$res){
					$this->M->rollback();
					$this->error($this->M->getError());
				}/*else{
					$result['type'] = $res[0]['type'];
				    $result['price']= $res[0]['price'];
				}*/
				
				//查询当前领用表已领用的数量
				$relts = D('inventoryInformation')->where(array('name'=>$result['name'],'unit'=>$result['unit'],'specification'=>$result['specification'],'belongs_department'=>D('ApplicationForm')->getSelfDepartment()))->select();
				$relt = D('useReturn')->where(array('name'=>$result['name'],'unit'=>$result['unit'],'specification'=>$result['specification'],'belongs_department'=>D('ApplicationForm')->getSelfDepartment()))->select();
				if($relt){
				    //构造库存数量
				    $inventory_num = D('inventoryInformation')->where(array('name'=>$result['name'],'unit'=>$result['unit'],'specification'=>$result['specification'],'belongs_department'=>D('ApplicationForm')->getSelfDepartment()))->getField('inventory_num');
				    $result['inventory_num'] = $inventory_num + $re['return_num'];
					//构造归还数量
					$return_sum = D('useReturn')->where(array('name'=>$result['name'],'unit'=>$result['unit'],'specification'=>$result['specification'],'belongs_department'=>D('ApplicationForm')->getSelfDepartment()))->sum("return_num");
					$result['return_num'] = $return_sum + $re['return_num'] ;
					$result['using_num']  = $relts[0]['total_num'] - $result['inventory_num'];
					if (M('inventoryInformation')->where(array('name'=>$result['name'],'unit'=>$result['unit'],'specification'=>$result['specification'],'belongs_department'=>D('ApplicationForm')->getSelfDepartment()))->save($result) !== false) {
						$this->M -> add();
						$this->M->commit();
						$this->success(L('ADD_SUCCESS'));
					} else {
						$this->M->rollback();
						$this->error($this->M->getError().$this->M->getLastSql());
					}
					
				}else{
					
					$this->M->rollback();
					$this->error("该用品资料出错了".$this->M->getLastSql());
					
				}
    		}
    		
    	}else{
    		$this->error($this->M->getError());
    	}
    }

    public function getData(){
        $list = D('UseReturn')->distinct(true)->where(array('info_status'=>1,'belongs_department'=>D('ApplicationForm')->getSelfDepartment()))->getField('name',true);
        $this->ajaxReturn($list);
    }
    public function getSpecByName($name){
        $list = D('UseReturn')->distinct(true)->where(array('info_status'=>1,'belongs_department'=>D('ApplicationForm')->getSelfDepartment(),'name'=>$name))->getField('specification',true);
        $this->ajaxReturn($list);
    }
    public function getUnitsBySpec($specification,$name){
        $list = D('UseReturn')->distinct(true)->where(array('info_status'=>1,'belongs_department'=>D('ApplicationForm')->getSelfDepartment(), 'specification'=>$specification, 'name'=>$name))->getField('unit',true);
        $this->ajaxReturn($list);
    }
    public function getMaxNum($unit,$name,$specification){
        $use_num = D('UseReturn')->where(array('info_status'=>1,'belongs_department'=>D('ApplicationForm')->getSelfDepartment(), 'unit'=>$unit, 'name'=>$name,'specification'=>$specification))->sum('use_num');
        $return_num = D('UseReturn')->where(array('info_status'=>1,'belongs_department'=>D('ApplicationForm')->getSelfDepartment(), 'unit'=>$unit, 'name'=>$name,'specification'=>$specification))->sum('return_num');
		$list = $use_num  -  $return_num;
        $this->ajaxReturn($list);
    }
	public function getMaxNums($unit,$name,$specification){
        $use_num = D('InventoryInformation')->where(array('info_status'=>1, 'unit'=>$unit, 'name'=>$name,'specification'=>$specification,'belongs_department'=>D('ApplicationForm')->getSelfDepartment()))->getField('use_num');
        $return_num = D('InventoryInformation')->where(array('info_status'=>1, 'unit'=>$unit, 'name'=>$name,'specification'=>$specification,'belongs_department'=>D('ApplicationForm')->getSelfDepartment()))->getField('return_num');
		$repair_num = D('InventoryInformation')->where(array('info_status'=>1, 'unit'=>$unit, 'name'=>$name,'specification'=>$specification,'belongs_department'=>D('ApplicationForm')->getSelfDepartment()))->getField('repair_num');
        $scrap_num = D('InventoryInformation')->where(array('info_status'=>1, 'unit'=>$unit, 'name'=>$name,'specification'=>$specification,'belongs_department'=>D('ApplicationForm')->getSelfDepartment()))->getField('scrap_num');
		$list = $use_num  -  $return_num - $scrap_num - $repair_num;
        $this->ajaxReturn($list);
    }





}